package org.nf.web.initializer;

import jakarta.servlet.MultipartConfigElement;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
import org.nf.web.WebApplicationInitializer;
import org.nf.web.config.Configure;
import org.nf.web.config.MvcConfig.MultipartConfig;
import org.nf.web.servlet.DispatcherServlet;

/**
 * @author wangl
 * @date 2024/3/19
 * 初始化DispatcherServlet
 */
public class DispatcherServletInitializer implements WebApplicationInitializer {

    private final static String SERVLET_NAME = "dispatcher";

    private final static String URL_PATTERN = "/";

    @Override
    public void onStartup(ServletContext servletContext) {
        initDispatcherServlet(servletContext);
    }

    private void initDispatcherServlet(ServletContext servletContext) {
        ServletRegistration.Dynamic registration = servletContext.addServlet(SERVLET_NAME, DispatcherServlet.class);
        registration.addMapping(URL_PATTERN);
        Configure config = (Configure) servletContext.getAttribute(Configure.class.getName());
        MultipartConfig multipartConfig = config.getMvc().getMultipart();
        //如果启用了文件上传，设置上传
        if (multipartConfig.getEnable()) {
            MultipartConfigElement configElement = new MultipartConfigElement(multipartConfig.getLocation(),
                    multipartConfig.getMaxFileSize(), multipartConfig.getMaxRequestSize(),
                    multipartConfig.getFileSizeThreshold());
            registration.setMultipartConfig(configElement);
        }
        registration.setLoadOnStartup(0);
    }
}